<script setup>
import {getToken, renderIcon} from "@/utils";
import {onMounted, watch} from "vue";
import api from "@/api";
import {NButton, NForm, NFormItem, NImage, NInput, NSelect, useMessage} from "naive-ui";
import TheIcon from "@/components/icon/TheIcon.vue";
const base_path = import.meta.env.VITE_BASE
const message = useMessage()
const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});
const today = new Date();
const emit = defineEmits(['call-parent'])

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  select_customer: {
    name: "",
    card_number: "--",
    user_level_name: "--",
    mobile: "--",
    bi_date: null,
    sex: "--",
    address:"--",
    car:[],
    desc:"",
    hkqd: "--",
    age: "--",
    created_at: "--",
    last_come: "--",
    identity: "--",
    avatar:'',
    level:"--",
    record_hobby: [],
    totals: {
      weimei: 0,
      cdp: 0,
      fujia: 0,
      other: 0,
      buy_money: 0,
      cases: 0,
      appoint_count: 0,
      return_count: 0,
      operation_count: 0,
      face_count: 0,
      test_count: 0,
      having_customers: 0,
      customers_level5: 0
    },
  },
  is_edit: false,
  config_sex: [{"id": 1, "name": "男"}, {"id": 2, "name": "女"}],
  config: [],
  user_all: [],
  search_loading: false,
  select_customers: [],
  show_assets:false,
  mx_loading:false,
  mx_names:["","储值","积分","优惠券","赠送金"],
  mx_type:1,
  mx_data:[],
  add_mode:false,
  card_loading:false,
  show_fenzhen:false,
  fenzhenForm:{
    type:1,
    remark:"",
    category_id:null,
    adviser_id:[],
    // shouli_uid:null,
    // hkqd:null,
    // dckf_uid:null,
    user_id:null,
    appoint_day: today.toLocaleDateString('en-CA'),
    appoint_time:null,
    is_sms:false,
  },
  advisers:[],
  sms:['是','否']
});

onMounted(() => {

  if(!props.infoData.user_id){
    //添加客户模式
    data.add_mode = true
    edit_info()
  }else{
    on_ref()
  }
})

function calculateAge(dateString){
  if(!dateString) return "--"
  const today = new Date()
  const parts = String(dateString).split(/[-/.]/)
  // 支持 yyyy-MM-dd / yyyy/M/d / yyyy.M.d
  const year = Number(parts[0])
  const month = Number(parts[1]) - 1
  const day = Number(parts[2])
  const birth = new Date(year, month, day)
  if (isNaN(birth.getTime())) return "--"
  let age = today.getFullYear() - birth.getFullYear()
  const m = today.getMonth() - birth.getMonth()
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  return age < 0 ? 0 : age
}

watch(() => data.select_customer.bi_date, (newVal) => {
  data.select_customer.age = calculateAge(newVal)
})

function update_info() {
  data.card_loading = true
  api.getCustomer({
    user_id: props.infoData.user_id,
  }).then((res) => {
    data.select_customer = res.data
    // 確保 totals 中的數值都是數字類型
    if (data.select_customer.totals) {
      data.select_customer.totals.weimei = Number(data.select_customer.totals.weimei) || 0
      data.select_customer.totals.cdp = Number(data.select_customer.totals.cdp) || 0
      data.select_customer.totals.fujia = Number(data.select_customer.totals.fujia) || 0
      data.select_customer.totals.other = Number(data.select_customer.totals.other) || 0
      data.select_customer.totals.buy_money = Number(data.select_customer.totals.buy_money) || 0
      data.select_customer.totals.cases = Number(data.select_customer.totals.cases) || 0
      data.select_customer.totals.appoint_count = Number(data.select_customer.totals.appoint_count) || 0
      data.select_customer.totals.return_count = Number(data.select_customer.totals.return_count) || 0
      data.select_customer.totals.operation_count = Number(data.select_customer.totals.operation_count) || 0
      data.select_customer.totals.face_count = Number(data.select_customer.totals.face_count) || 0
      data.select_customer.totals.test_count = Number(data.select_customer.totals.test_count) || 0
      data.select_customer.totals.having_customers = Number(data.select_customer.totals.having_customers) || 0
      data.select_customer.totals.customers_level5 = Number(data.select_customer.totals.customers_level5) || 0
    }
    data.card_loading = false
    data.select_customers = [{'all_name':data.select_customer.parent_name,'id':data.select_customer.parent_uid}]
    console.log(data.select_customers)
  })
  return true
}

function save_info() {
  if(data.add_mode){
    api.createCustomer(data.select_customer).then((res) => {
      data.select_customer.user_id = res.data.id
      props.infoData.user_id = res.data.id
      message.success('添加成功')
      data.add_mode = false
      cancel_info()
      emit('call-parent')
      on_ref()
    })

  }else{
    api.CustomerEdit(data.select_customer).then((res) => {
    message.success('编辑成功')
    emit('call-parent')
    cancel_info()
    on_ref()
  })

  }

  return true
}

function get_config() {
  if (data.config.length === 0) {
    api.getConfig().then((res) => {
      data.config = res.data
    })
    api.getUserList({page_size:10000}).then((res) => {
      data.user_all = res.data
    })
    api.getUserList({
      type: 3
    }).then((res) => {
      data.advisers = res.data
    })
  }
}

function search_customer(query) {
  data.search_loading = true
  api.getCustomers({keyword: query}).then((res) => {
    data.select_customers = res.data.items
    data.search_loading = false
  })
}

function on_ref() {
  update_info()
}

function edit_info() {
  get_config()
  data.is_edit = true
}

function cancel_info() {
  data.is_edit = false
}

function show_mx(type) {
  get_mx(type)
  data.show_assets = true
  data.mx_type = type
}

function get_mx(type){
  data.mx_loading = true
  api.getAssets({
    user_id:data.select_customer.user_id,
    type:type
  }).then((res) => {
      data.mx_data = res.data.items
    data.mx_loading = false
    })
}

const customRequestMethod = (options) => {
    console.log(options, 'options');
    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((ret_data) => {
            if (ret_data.code === 200) {
                data.select_customer.avatar = ret_data.data.url
                message.success('头像上传成功');
                options.onProgress(ret_data);
            } else {
                message.error(ret_data.msg);
            }
        })
}

function on_fenzhen(){
  api.getProjectIni().then((res) => (data.data_ini = res.data))
  api.getUserList({page_size:10000}).then((res) => {
      data.user_all = res.data
    })

  api.getUserList({
    type: 3
  }).then((res) => {
    data.advisers = res.data
  })
  data.show_fenzhen =true
}

function save_fenzhen(){
  data.fenzhenForm.user_id = props.infoData.user_id
  data.fenzhenForm.appoint_time = data.fenzhenForm.appoint_day+' 00:00:00'
  api.createAppointment(data.fenzhenForm).then((res) => {
    message.success('添加成功')
    data.show_fenzhen=false
  })
}

</script>

<template>

    <NScrollbar style="position:relative;height:calc(100vh - 106px);padding-bottom: 60px">
      <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 225px);">
        <div class="info1">
          <div class="data_card" @click="show_mx(1)">
            <div class="icon">
              <component :is="renderIcon('mdi-account-cash-outline', { size: 30,color:'#fff' })"/>
            </div>
            <div class="con">
              {{ (data.select_customer.totals?.weimei || 0).toFixed(2) }}<br>
              <span class="tag">储值余额 ></span>
            </div>
          </div>
          <div class="data_card" style="background: rgba(146,82,121,0.4);" @click="show_mx(2)">
            <div class="icon" style="background: rgba(146,82,121,1);">
              <component :is="renderIcon('material-symbols:copyright-rounded', { size: 30,color:'#fff' })"/>
            </div>
            <div class="con" style="color: rgba(146,82,121,1);">
              {{ data.select_customer.totals.cdp }}<br>
              <span class="tag">积分余额 ></span>
            </div>
          </div>
          <div class="data_card" style="background: rgba(123,79,146,0.4);" @click="show_mx(3)">
            <div class="icon" style="background: rgba(123,79,146,1);">
              <component :is="renderIcon('mdi-ticket-percent-outline', { size: 30,color:'#fff' })"/>
            </div>
            <div class="con" style="color: rgba(123,79,146,1);">
              {{ data.select_customer.totals.fujia }}<br>
              <span class="tag">优惠券余额 ></span>
            </div>
          </div>

          <div class="data_card" style="background: rgba(80,79,146,0.4);" @click="show_mx(4)">
            <div class="icon" style="background: rgba(80,79,146,1);">
              <component :is="renderIcon('mdi-table-split-cell', { size: 30,color:'#fff' })"/>
            </div>
            <div class="con" style="color: rgba(80,79,146,1);">
              {{ data.select_customer.totals.free }}<br>
              <span class="tag">赠送金 ></span>
            </div>
          </div>

        </div>
        <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
          <template #header>
            <n-h6 prefix="bar" style="margin: 0;font-size: 18px">基础信息</n-h6>
          </template>
          <div class="info1">
            <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
              <n-descriptions-item label="姓名">
                <div v-if="!data.is_edit" style="display: flex;align-items: center">
                   <NImage  width="30" style="border-radius: 5px;margin-right: 15px;"
                            :src="data.select_customer.avatar"></NImage>
                   <span>{{ data.select_customer.name }}</span>
                </div>
                <div v-else  style="display: flex;align-items: center">
                  <NImage  width="30" style="border-radius: 5px;margin-right: 15px;"
                            :src="data.select_customer.avatar" v-if="data.select_customer.avatar"></NImage>
                  <n-input v-model:value="data.select_customer.name"/>
                  <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" :max="1"
                      :show-file-list=false :custom-request="customRequestMethod" list-type="image">
                      <NButton style="margin-left: 5px">更换头像</NButton>
                  </NUpload>
                </div>


              </n-descriptions-item>
              <n-descriptions-item label="病历号">
                {{ data.select_customer.card_number }}
    <!--            <span v-if="!data.is_edit">{{ data.select_customer.card_number }}</span>-->
    <!--            <n-input v-else v-model:value="data.select_customer.card_number"/>-->
              </n-descriptions-item>
              <n-descriptions-item label="会员级别">
                <span>{{ data.select_customer.user_level_name }}</span>
                <!--      <n-input v-else  v-model:value="data.select_customer.user_level_name"/>-->
              </n-descriptions-item>
              <n-descriptions-item label="电话">
                <span v-if="!data.is_edit">{{ data.select_customer.mobile }}</span>
                <n-input v-else v-model:value="data.select_customer.mobile"/>
              </n-descriptions-item>
              <n-descriptions-item label="会员生日">
                <span v-if="!data.is_edit">{{ data.select_customer.bi_date }}</span>
    <!--            <n-input v-else v-model:value="data.select_customer.bi_date"/>-->
                <n-date-picker  v-else
                                      v-model:formatted-value="data.select_customer.bi_date"
                                      value-format="yyyy-MM-dd"
                                      type="date"
                                      clearable
                                      placeholder="会员生日"
                                    />
              </n-descriptions-item>
              <n-descriptions-item label="地址">
                <span v-if="!data.is_edit">{{ data.select_customer.address }}</span>
                <n-input v-else v-model:value="data.select_customer.address"/>
              </n-descriptions-item>
              <n-descriptions-item label="身份证">
                <span v-if="!data.is_edit">{{ data.select_customer.identity }}</span>
                <n-input v-else v-model:value="data.select_customer.identity"/>
              </n-descriptions-item>
              <n-descriptions-item label="会员年龄">
                <span v-if="!data.is_edit">{{ data.select_customer.age }}</span>
                <n-input v-else v-model:value="data.select_customer.age"/>
              </n-descriptions-item>
              <n-descriptions-item label="会员性别">
                <span v-if="!data.is_edit">{{ data.select_customer.sex }}</span>
                <NSelect v-else
                         v-model:value="data.select_customer.sex"
                         :options="data.config_sex"
                         placeholder="请选择会员性别"
                         label-field="name"
                         value-field="id"
                />
              </n-descriptions-item>
              <n-descriptions-item label="登记时间">{{ data.select_customer.created_at }}</n-descriptions-item>
              <n-descriptions-item label="上次到店">{{ data.select_customer.last_come }}</n-descriptions-item>
              <n-descriptions-item label="渠道来源">
                <span v-if="!data.is_edit">{{ data.select_customer.hkqd }}</span>
                <NSelect v-else
                         v-model:value="data.select_customer.hkqd"
                         :options="data.config.hkqd"
                         placeholder="请选择渠道来源"
                         label-field="name"
                         value-field="name"
                />
              </n-descriptions-item>
              <n-descriptions-item label="介绍人">
                <span v-if="!data.is_edit">{{ data.select_customer.parent_name }}</span>
                <NSelect v-else
                         v-model:value="data.select_customer.parent_uid"
                         :options="data.select_customers"
                         placeholder="输入姓名/病历号/手机号搜索"
                         filterable
                         label-field="all_name"
                         value-field="id"
                         style="width: 100%"
                         :loading="data.search_loading"
                         remote
                         clearable
                         @search="search_customer"/>
              </n-descriptions-item>
              <n-descriptions-item label="渠道等级">
                <span v-if="!data.is_edit">{{ data.select_customer.level_name }}</span>
                <NSelect v-else
                          v-model:value="data.select_customer.level"
                          :options="data.config.vip_level"
                          placeholder="请选择渠道等级"
                          filterable
                          label-field="name"
                          value-field="id"
                          style="width: 100%"
                        />
              </n-descriptions-item>



              <n-descriptions-item label="所属顾问">
                <span v-if="!data.is_edit">{{ data.select_customer.butler_name }}</span>
                <NSelect v-else
                         v-model:value="data.select_customer.butler_id"
                         :options="data.advisers"
                         placeholder="请选择所属顾问"
                         label-field="name"
                         value-field="id"
                         filterable
                />
              </n-descriptions-item>
              <n-descriptions-item label="所属开发">
                <span v-if="!data.is_edit">{{ data.select_customer.bd_name }}</span>
                <NSelect v-else
                         v-model:value="data.select_customer.bd_id"
                         :options="data.user_all"
                         placeholder="请选择所属开发"
                         label-field="name"
                         value-field="id"
                         filterable
                />
              </n-descriptions-item>
              <n-descriptions-item label="备注">
                <span v-if="!data.is_edit">{{ data.select_customer.desc }}</span>
                <n-input v-else v-model:value="data.select_customer.desc"/>
              </n-descriptions-item>
              <n-descriptions-item label="车牌号">
                <span v-if="!data.is_edit">{{ data.select_customer.car }}</span>
<!--                <n-input v-else v-model:value="data.select_customer.car"/>-->
                 <n-dynamic-tags v-else v-model:value="data.select_customer.car" />
              </n-descriptions-item>
            </n-descriptions>
          </div>
        </n-card>
        <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
          <template #header>
            <n-h6 prefix="bar" style="margin: 0;font-size: 18px">汇总统计</n-h6>
          </template>
          <div class="info1" v-if="!data.add_mode" >
            <n-descriptions style="width: 100%;" label-placement="left" bordered :column="3">
              <n-descriptions-item label="合计消费">{{ data.select_customer.totals.buy_money }}万</n-descriptions-item>
              <n-descriptions-item label="合计操作">{{ data.select_customer.totals.cases }}</n-descriptions-item>
              <n-descriptions-item label="预约次数">{{ data.select_customer.totals.appoint_count }}</n-descriptions-item>
              <n-descriptions-item label="回访次数">{{ data.select_customer.totals.return_count }}</n-descriptions-item>
              <n-descriptions-item label="剩余划扣">{{ data.select_customer.totals.operation_count }}</n-descriptions-item>
              <n-descriptions-item label="健康顾问次数">{{ data.select_customer.totals.face_count }}</n-descriptions-item>
              <n-descriptions-item label="护士次数">{{ data.select_customer.totals.test_count }}</n-descriptions-item>
              <n-descriptions-item label="推荐人数">{{ data.select_customer.totals.having_customers }}</n-descriptions-item>
              <n-descriptions-item label="带客人数">{{ data.select_customer.totals.customers_level5 }}</n-descriptions-item>
            </n-descriptions>
          </div>
          <n-empty v-else description="请先添加客户资料并保存" style="margin: 50px"></n-empty>
        </n-card>
        <n-card size="small" content-style="padding: 0px;" :bordered="false" :segmented="{content: true,footer: 'soft',}">
          <template #header>
            <n-h6 prefix="bar" style="margin: 0;font-size: 18px">近期活动日志</n-h6>
          </template>
          <div class="info1" v-if="!data.add_mode">
            <n-scrollbar x-scrollable>
              <div style="white-space: nowrap;width: 100%;display: flex;padding-bottom: 20px">
                   <n-card embedded v-for="item in data.select_customer.logs" style="margin-right: 10px;width: auto;" size="small" >
                    <template #header>
                      <span style="font-size: 12px">{{item.time}}</span>
                    </template>
                    {{item.remark}}
                  </n-card>
                </div>
            </n-scrollbar>
          </div>
          <n-empty v-else description="请先添加客户资料并保存" style="margin: 50px"></n-empty>
        </n-card>
      </n-spin>


      <div class="tools">
        <n-button v-if="!data.is_edit" type="primary" size="large" style="margin-left:10px" @click="edit_info">
          <TheIcon icon="material-symbols:save-sharp" :size="18" class="mr-5"/>
          编辑
        </n-button>
        <n-button v-if="data.is_edit&&!data.add_mode" type="primary" size="large" style="margin-left:10px" @click="cancel_info">
          <TheIcon icon="material-symbols:cancel" :size="18" class="mr-5"/>
          取消编辑
        </n-button>

        <n-button v-if="data.is_edit" type="primary" size="large" style="margin-left:10px" @click="save_info">
          <TheIcon icon="material-symbols:save-sharp" :size="18" class="mr-5"/>
          保存
        </n-button>

        <n-button v-if="!data.is_edit" type="primary" size="large" style="margin-left:10px" @click="on_fenzhen">
        <TheIcon icon="material-symbols:grid-view-rounded" :size="18" class="mr-5"/>
          分诊
        </n-button>
      </div>
    </NScrollbar>


  <n-drawer v-model:show="data.show_assets" width="500px">
        <n-drawer-content :title="data.mx_names[data.mx_type]+'明细'" closable>
          <n-scrollbar style="max-height: 100%;padding-right: 10px"  content-style="overflow: hidden;">
          <n-spin :show="data.mx_loading" style="--n-opacity-spinning:0.1;height: 100%">
          <n-card style="margin-bottom: 20px" v-for="item in data.mx_data" size="small" :segmented="{content: true,footer: 'soft',}">
            <template #header>
              <div style="display: flex; align-items: center;justify-content: flex-start">
                <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                  <div style="display: flex">
                  <n-button type="info" dashed size="large">编号:{{item.id}}</n-button>
                <div style="height:40px;line-height:20px;margin-left: 10px">
                  <span style="margin-right: 5px">
                    {{item.nums}}
                  </span>
                  <br>
                  <span style="font-size: 12px;color:#747586">发生于:{{item.time}}</span>
                </div>
                  </div>
                </n-h6>
              </div>
            </template>

            <template #header-extra v-if="data.mx_type!==3">
              <n-button type="primary" v-if="item.use_type===1">
                <TheIcon icon="material-symbols:add-moderator-outline-rounded" :size="18" class="mr-5" />增加</n-button>
              <n-button type="error" v-if="item.use_type===2">
                <TheIcon icon="material-symbols:encrypted-minus-circle-rounded" :size="18" class="mr-5" />减少</n-button>
            </template>

            <template #header-extra v-if="data.mx_type===3">
             <n-button type="error" v-if="item.order_id_use>0">
                <TheIcon icon="material-symbols:encrypted-minus-circle-rounded" :size="18" class="mr-5" />已使用</n-button>
             <n-button type="primary" v-else>
                <TheIcon icon="material-symbols:add-moderator-outline-rounded" :size="18" class="mr-5" />未使用</n-button>

            </template>

            <div style="display: flex;font-size: 16px;color: #aaa;align-items: center">
              {{item.come}}
            </div>

          </n-card>
          </n-spin>
          </n-scrollbar>
        </n-drawer-content>
    </n-drawer>

   <n-modal v-model:show="data.show_fenzhen" preset="dialog" title="Dialog">
    <template #header>
      <div>分诊添加</div>
    </template>
    <NForm
              label-placement="left"
              label-align="left"
              :label-width="80"
              :model="data.fenzhenForm"
              style="margin-top: 20px;width: 300px"
          >
            <NFormItem label="咨询顾问" path="adviser_id">
                  <NSelect
                     v-model:value="data.fenzhenForm.adviser_id"
                     :options="data.advisers"
                     placeholder="请选择咨询顾问"
                     label-field="name"
                     value-field="id"
                     multiple
                     filterable
            />
            </NFormItem>
            <NFormItem label="短信推送" path="is_sms">
                  <n-switch v-model:value="data.fenzhenForm.is_sms"/>
            </NFormItem>

          </NForm>
    <template #action>
      <n-button type="primary" size="large" @click="save_fenzhen">
        <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
        保存
      </n-button>
    </template>
  </n-modal>

</template>

<style scoped>
.tools{
  position: absolute;
  bottom:0;right:0;
  width:100%;
  height:60px;
  background: #f3f3f3;
  z-index: 99;
  display: flex;
  align-items: center
}
.info1 {
  width: 100%;
  padding: 20px;
  display: flex;

  .data_card {
    width: 25%;
    height: 100px;
    margin-right: 20px;
    background: rgba(200, 115, 115, 0.2);
    color: #fff;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .icon {
      margin-right: 20px;
      background: rgba(200, 115, 115, 1);
      padding: 5px;
      border-radius: 5px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .con {
      line-height: 20px;
      font-size: 25px;
      color: rgba(200, 115, 115, 1);

      .tag {
        font-size: 14px;
        color: #000;
        font-weight: normal;
      }
    }
  }
}
</style>